package com.sun.config;

import com.sun.model.OperateLogInfo;
import com.sun.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.joda.time.LocalDateTime;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetAddress;


@Component
@Aspect
@Slf4j
public class LogAspect {

    @Resource
    private LogService logService;

    @Pointcut("@annotation(com.sun.annotation.Log)")
    public void log() {
    }


    @Around("log()")
    public void beforLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String startDate = LocalDateTime.now().toString("yyyy/MM/dd HH:mm:ss");
        log.info("开始执行时间startDate:{}", startDate);
        InetAddress host = InetAddress.getLocalHost();
        String ip = host.getHostAddress();
        log.info("执行机器ip:{}", ip);
        String methodName = joinPoint.getSignature().getName();
        log.info("当前操作的方法名称:{}", methodName);
        Object result = joinPoint.proceed();
        log.info("执行结果为:{}", result);
        String endDate = LocalDateTime.now().toString("yyyy/MM/dd HH:mm:ss");
        log.info("执行结束时间为:{}", endDate);

        OperateLogInfo logInfo = new OperateLogInfo();
        logInfo.setLoginIp(ip).setStartDate(startDate).setEndDate(endDate).setMethodName(methodName);
        logService.saveLogInfo(logInfo);
    }
}
